from google.appengine.ext.webapp import template
from google.appengine.ext import db

from views.game_server import GameServer

from views.base import ViewBase
from models import Server, Room, Player, Note

class Admin(ViewBase):
    gs = GameServer()

    def index(self, request):
        sq = Server.all()
        nq = Note.gql("WHERE outdated=False ORDER BY version DESC")
        self.context['servers'] = sq.fetch(sq.count())
        self.context['notes'] = nq.fetch(nq.count())

        return template.render(self.get_template('admin/index.html'), self.context)

    def remove_server(self, request):
        s = Server.gql("WHERE id = :id", id=request.get('server_id', 0)).get()
        self.gs._drop_rooms(s)
        s.delete()

        return self.index(request)

    def modify_note(self, request):
        if not request.get('version', None):
            self.context['note'] = Note(version="", html=db.Text("", encoding="utf-8"))
        else:
            self.context['note'] = Note.gql("WHERE version = :version ORDER BY version DESC", version=request.get('version')).get()

        return template.render(self.get_template('admin/edit_notes.html'), self.context)

    def outdate_note(self, request):
        n = Note.gql("WHERE version = :version ORDER BY version DESC", version=request.get('version')).get()
        n.outdated = True
        n.put()

        if n.outdated:
            return self.index(request)

    def save_note(self, version, notes):
        n = Note.gql("WHERE version = :version", version=version)

        if n.count() == 0:
            n = Note(version=version, html=db.Text(notes))
        else:
            n = n.get()
            n.html = notes


        n.put()
